  package com.example.poem.activity;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.poem.R;
import com.example.poem.api.Api;
import com.example.poem.api.ApiConfig;
import com.example.poem.api.NetworkCallback;
import com.example.poem.entity.LoginResponse;
import com.example.poem.util.StringUtils;
import com.google.gson.Gson;

import java.util.HashMap;


  public class LoginActivity extends BaseActivity {

    EditText etAccount;
    EditText etPwd;
    Button btnLogin;

    @Override
    protected int initLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        etAccount = findViewById(R.id.et_account);
        etAccount.setText("root");
        etPwd = findViewById(R.id.et_pwd);
        etPwd.setText("123456");
        btnLogin = findViewById(R.id.btn_login);
    }

    @Override
    protected void initData() {
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String account = etAccount.getText().toString().trim();
                String pwd = etPwd.getText().toString().trim();
                login(account,pwd);
            }
        });
    }

    private void login(String account,String pwd) {
        if(StringUtils.isEmpty(account)){
            showToast("请输入账号");
            return;
        }
        if(StringUtils.isEmpty(pwd)){
            showToast("请输入密码");
            return;
        }
        HashMap<String,Object> params = new HashMap<>();
        params.put("mobile",account);
        params.put("password",pwd);
        Api.config(ApiConfig.LOGIN,params).postRequest(mContext,new NetworkCallback() {
            @Override
            public void onSuccess(String result) {
                Log.d("onSuccess",result);
                Gson gson = new Gson();
                LoginResponse loginResponse = gson.fromJson(result,LoginResponse.class);
                if(loginResponse.getCode()==0){
                    String token = loginResponse.getToken();
                    Log.d("abcd",token);
                    saveStringToSp("token",token);
                    navigateToWithFlags(HomeActivity.class
                            , Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                    showToastSync("登陆成功");
                }else{
                    showToastSync("登陆失败");
                }
            }

            @Override
            public void onFailure(Exception e) {
                Log.e("onFailure",e.toString());
            }
        });
    }
}